using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Commands;
using TerritoryGame.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace TerritoryGame.Application.Services;

/// <summary>
/// 系统服务实现
/// </summary>
public class AppSystemService : IAppSystemService
{
    private readonly TerritoryGameDbContext _db;

    public AppSystemService(TerritoryGameDbContext db)
    {
        _db = db;
    }

    /// <summary>
    /// 获取系统统计信息
    /// </summary>
    public async Task<ApiResult> GetSystemStatisticsAsync()
    {
        try
        {
            var totalUsers = await _db.Users.Where(u => !u.IsDeleted).CountAsync();
            var activeUsers = await _db.Users.Where(u => !u.IsDeleted && u.IsActive).CountAsync();
            
            var statistics = new
            {
                TotalUsers = totalUsers,
                ActiveUsers = activeUsers,
                TotalStorageUsed = 0, // 暂时设为0，因为没有文档存储
                DocumentStatusCounts = new Dictionary<string, int>(),
                ConversationModelCounts = new Dictionary<string, int>()
            };

            return ApiResult.Success("获取系统统计信息成功", statistics);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统统计信息失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统分析报告
    /// </summary>
    public async Task<ApiResult> GetSystemAnalyticsAsync()
    {
        try
        {
            // 最近7天的数据
            var sevenDaysAgo = DateTime.UtcNow.AddDays(-7);
            
            var dailyUsers = await _db.Users
                .Where(u => u.CreatedAt >= sevenDaysAgo)
                .GroupBy(u => u.CreatedAt.Date)
                .Select(g => new { Date = g.Key, Count = g.Count() })
                .OrderBy(x => x.Date)
                .ToListAsync();

            var analytics = new
            {
                DailyUsers = dailyUsers,
                AnalysisPeriod = "最近7天"
            };

            return ApiResult.Success("获取系统分析报告成功", analytics);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统分析报告失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统健康状态
    /// </summary>
    public async Task<ApiResult> GetSystemHealthAsync()
    {
        try
        {
            // 测试数据库连接
            var usersCount = await _db.Users.CountAsync();
            
            var healthStatus = new
            {
                Database = usersCount >= 0 ? "正常" : "异常",
                Api = "正常",
                Overall = "正常",
                Timestamp = DateTime.UtcNow
            };

            return ApiResult.Success("获取系统健康状态成功", healthStatus);
        }
        catch (Exception ex)
        {
            var healthStatus = new
            {
                Database = "异常",
                Api = "正常",
                Overall = "异常",
                Error = ex.Message,
                Timestamp = DateTime.UtcNow
            };

            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, "系统健康检查失败");
        }
    }

    /// <summary>
    /// 获取用户活动统计
    /// </summary>
    public async Task<ApiResult> GetUserActivityStatsAsync()
    {
        try
        {
            var activeUsers = await _db.Users
                .Where(u => !u.IsDeleted && u.LastActivityTime.HasValue && u.LastActivityTime >= DateTime.UtcNow.AddDays(-1))
                .CountAsync();

            var totalUsers = await _db.Users.Where(u => !u.IsDeleted).CountAsync();
            var userActivityRate = totalUsers > 0 ? (double)activeUsers / totalUsers * 100 : 0;

            var stats = new
            {
                ActiveUsers = new
                {
                    Value = activeUsers,
                    Unit = "用户",
                    Description = "过去24小时内有活动的用户"
                },
                TotalUsers = totalUsers,
                UserActivityRate = Math.Round(userActivityRate, 2),
                LastUpdated = DateTime.UtcNow
            };

            return ApiResult.Success("获取用户活动统计成功", stats);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户活动统计失败: {ex.Message}");
        }
    }
}
